//
//  TKL_addBlogVC.m
//  TKL_EnPro
//
//  Created by 雅恩三河科技 on 2018/12/11.
//  Copyright © 2018年 MrZhang. All rights reserved.
//

//
//                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
//            __.'              ~.   .~              `.__
//          .'//                  \./                  \\`.
//        .'//                     |                     \\`.
//      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \\`.
//    .'//.-"                 `-.  |  .-'                 "-.\\`.
//  .'//______.============-..   \ | /   ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
//

#import "TKL_addBlogVC.h"
#import <AliyunOSSiOS/OSSService.h>
@interface TKL_addBlogVC ()<UITextViewDelegate,TZImagePickerControllerDelegate>
@property(nonatomic,strong)UITextView* inputText;
@property(nonatomic,strong)UILabel* topLab;
@property(nonatomic,strong)UIButton* loginBtn;
@property(nonatomic,strong)UIScrollView* imageScroll;
@property(nonatomic,strong)UIImageView* addIV;
@property(nonatomic,strong)NSString* imageStr;
@end

@implementation TKL_addBlogVC
#pragma mark - getter and setter
-(UIImageView *)addIV
{
    if (!_addIV) {
        @WeakSelf;
        _addIV=[[UIImageView alloc] init];
        _addIV.x=20;
        _addIV.y=self.inputText.bottom+WFCGFloatY(15);
        _addIV.width=WFCGFloatY(80);
        _addIV.height=WFCGFloatY(80);
        _addIV.backgroundColor=[UIColor whiteColor];
        _addIV.image=[UIImage imageNamed:@"add_iamge"];
        
        [_addIV addTapGestureRecognizerWithDelegate:self Block:^(NSInteger tag) {
            
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePickerVc.allowTakePicture=NO;
            imagePickerVc.allowPickingOriginalPhoto=NO;
            // You can get the photos by block, the same as by delegate.
            // 你可以通过block或者代理，来得到用户选择的照片.
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                [selfp uploadImage:photos[0]];
        
            }];
            [self presentViewController:imagePickerVc animated:YES completion:nil];
        }];
    }
    return _addIV;
}
-(UIButton *)loginBtn
{
    if (!_loginBtn) {
        _loginBtn = [[UIButton alloc]init];
        _loginBtn.frame = WFCGRectMake(36, 196+[self topShelterHeight]+WFCGFloatY(90), 303, 41);
        [_loginBtn setTitle:@"发布" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_loginBtn setBackgroundColor:Main_Color forState:UIControlStateNormal];
        [WFFunctions WFUIaddbordertoView:_loginBtn radius:WFCGFloatY(41/2) width:0 color:[UIColor clearColor]];
        _loginBtn.titleLabel.font = SYSTEMFONT(16);
        @WeakSelf;
        [_loginBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
            if ([WFFunctions WFStrCheckEmpty:selfp.inputText.text]) {
                [FTIndicator showErrorWithMessage:@"请输入内容"];
                return;
            }
            if ([WFFunctions WFStrCheckEmpty:selfp.imageStr]) {
                [FTIndicator showErrorWithMessage:@"请选择图片"];
                return;
            }
            
            [selfp requestPPAddComment:selfp.inputText.text];
        }];
    }
    return _loginBtn;
}
-(UITextView *)inputText
{
    if (!_inputText) {
        _inputText=[[UITextView alloc] init];
        _inputText.delegate=self;
        _inputText.x=0;
        _inputText.y=[self topShelterHeight]+10;
        _inputText.width=SCREEN_WIDTH;
        _inputText.height=WFCGFloatY(160);
        _inputText.placeholder=@"请输入您的发布内容......";
        _inputText.font=SYSTEMFONT(15);
    }
    return _inputText;
}
#pragma mark - event
#pragma mark - method
-(void)initilization
{
    [self setNavgationTheme:0];
    [self viewModelBand];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.navigationItem.title = @"发布帖子";
    [self.view addSubview:self.inputText];
    [self.view addSubview:self.topLab];
    [self.view addSubview:self.loginBtn];
    [self.view addSubview:self.addIV];
}

-(void)reloadImageVIews
{
   
}
-(void)viewModelBand
{
    @WeakSelf;
//    GCBaseObservationModel* saleOber=[GCBaseObservationModel new];
//    saleOber.keyPath=@"success";
//    saleOber.observation=self.viewModel;
//    saleOber.handler = ^(NSString *keyPath) {
//        [selfp.navigationController popViewControllerAnimated:YES];
//    };
//    [self registObservation:saleOber];
}
-(void)reloadData
{
    
}
-(void)reloadView
{
    
}
#pragma mark - life
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initilization];
}
-(void)requestImage:(UIImage*)myIV
{
    @WeakSelf;
    NSMutableDictionary* para=[NSMutableDictionary new];
    [para setObject:@"1" forKey:@"deviceType"];
    [para setObject:@"1" forKey:@"type"];
    [[InterfaceManager shareInterface] requestAllInterface:@"http://101.201.171.131:8080/rest/api/photo/ossToken" para:para handler:^(NSDictionary *info, InterfaceStatusModel *infoModel) {
        NSDictionary* dic=[info objectForKey:@"data"];
        [selfp uploadImage:myIV data:dic];

    }];
    
    
}
-(void)uploadImage:(UIImage*)image data:(NSDictionary*)data
{
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:[data objectForKey:@"accessKeyId"] secretKeyId: [data objectForKey:@"accessKeySecret"] securityToken: [data objectForKey:@"securityToken"]];
    OSSClient* client = [[OSSClient alloc] initWithEndpoint:@"https://oss-cn-beijing.aliyuncs.com" credentialProvider:credential];
    
    
    
    NSDate *senddate = [NSDate date];
    NSString *date2 = [NSString stringWithFormat:@"%ld%d", (long)[senddate timeIntervalSince1970],1];
    NSString *imageName = [NSString stringWithFormat:@"%@/%@gyios", kProduct, date2];
    

    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // 必填字段
    put.bucketName = kBucketName;
    put.objectKey = imageName;
     put.uploadingData = UIImageJPEGRepresentation(image, 0.6); // 直接上传NSData
    // 设置Content-Type，可选
    put.contentType = @"application/octet-stream";

    // 进度设置，可选
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask * putTask = [client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"-----%@",task.result);
            NSLog(@"upload object success!");
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
    
    
}

-(void)requestPPAddComment:(NSString*)content
{
    @WeakSelf;
    [FTIndicator showProgressWithMessage:@"正在发布"];
    //http://101.201.171.131:8080/rest/api/community/comment/add
    NSMutableDictionary* para=[NSMutableDictionary new];
    [para setObject:content forKey:@"content"];
    [para setObject:[TKL_LoginViewModel shareInterface].infoModel.uuid forKey:@"userUuid"];

    if (![WFFunctions WFStrCheckEmpty:self.imageStr])
    {
        [para setObject:self.imageStr forKey:@"cover"];
    }
    [para setObject:content forKey:@"title"];
    [para setObject:@"21" forKey:@"topicIds"];
    [para setObject:@"0" forKey:@"posterDraftId"];
    [para setObject:@"1" forKey:@"longShort"];

    [[InterfaceManager shareInterface] requestAllInterface:@"http://101.201.171.131:8080/rest/api/community/poster/publish" para:para handler:^(NSDictionary *info, InterfaceStatusModel *infoModel) {
        [FTIndicator showSuccessWithMessage:@"发布成功"];
        [selfp.navigationController popViewControllerAnimated:YES];
    }];
}
#pragma mark - delegate

-(void)uploadImage:(UIImage*)upimage
{
    //设置服务名
    [FTIndicator showProgressWithMessage:@"正在上传图片"];
    
    NSData *data = UIImagePNGRepresentation(upimage);
    
    NSString* orderNum=[NSString stringWithFormat:@"RD20190050%d",arc4random() % 100000];
    BmobFile *file = [[BmobFile alloc]initWithFileName:[NSString stringWithFormat:@"%@.png",orderNum] withFileData:data];
    [file saveInBackground:^(BOOL isSuccessful, NSError *error) {
        //如果文件保存成功，则把文件添加到filetype列
        if (isSuccessful) {
            [FTIndicator showSuccessWithMessage:@"图片保存成功"];
            self.imageStr=file.url;
            [_addIV sd_setImageWithURL:[NSURL URLWithString:self.imageStr]];
            
        }else{
            //进行处理
        }
    }];
    

    
    
    
    
    
    
    
//    NSData *tmpData = UIImageJPEGRepresentation(upimage, 0.5);
//    UpYunFormUploader *up = [[UpYunFormUploader alloc] init];
//    
//    NSString *bucketName = @"yannihealth";
//    [up uploadWithBucketName:bucketName
//                    operator:@"wangjin"
//                    password:@"wangjin_888"
//                    fileData:tmpData
//                    fileName:nil
//                     saveKey:[self getSaveKeyWith:@"jpg"]
//             otherParameters:nil
//                     success:^(NSHTTPURLResponse *response,
//                               NSDictionary *responseBody) {
//                         NSLog(@"上传成功 responseBody：%@", responseBody);
//                         [FTIndicator showSuccessWithMessage:@"上传成功"];
//                         self.imageStr=[NSString stringWithFormat:@"https://cdn.yannihealth.com%@",[responseBody objectForKey:@"url"]];
//                         [_addIV sd_setImageWithURL:[NSURL URLWithString:self.imageStr]];
//                     }
//                     failure:^(NSError *error,
//                               NSHTTPURLResponse *response,
//                               NSDictionary *responseBody) {
//                         [FTIndicator showErrorWithMessage:@"上传失败"];
//                     }
//     
//                    progress:^(int64_t completedBytesCount,
//                               int64_t totalBytesCount) {
//                    }];
    
}


- (NSString * )getSaveKeyWith:(NSString *)suffix {
    return [NSString stringWithFormat:@"%@/%@.%@", AvatarUpUrl,[self getDateString], suffix];
}

- (NSString *)getDateString {
    NSDate *curDate = [NSDate date];//获取当前日期
    NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy/MM/dd"];//这里去掉 具体时间 保留日期
    NSString * curTime = [formater stringFromDate:curDate];
    curTime = [NSString stringWithFormat:@"%@/%.0f%d", curTime, [curDate timeIntervalSince1970],[self getRandomNumber]];
    return curTime;
    
}
-(int)getRandomNumber
{
    return arc4random()%100;
    
}
@end


/*
 11111111111111111111111111111111111111001111111111111111111111111
 11111111111111111111111111111111111100011111111111111111111111111
 11111111111111111111111111111111100001111111111111111111111111111
 11111111111111111111111111111110000111111111111111111111111111111
 11111111111111111111111111111000000111111111111111111111111111111
 11111111111111111111111111100000011110001100000000000000011111111
 11111111111111111100000000000000000000000000000000011111111111111
 11111111111111110111000000000000000000000000000011111111111111111
 11111111111111111111111000000000000000000000000000000000111111111
 11111111111111111110000000000000000000000000000000111111111111111
 11111111111111111100011100000000000000000000000000000111111111111
 11111111111111100000110000000000011000000000000000000011111111111
 11111111111111000000000000000100111100000000000001100000111111111
 11111111110000000000000000001110111110000000000000111000011111111
 11111111000000000000000000011111111100000000000000011110001111111
 11111110000000011111111111111111111100000000000000001111100111111
 11111111000001111111111111111111110000000000000000001111111111111
 11111111110111111111111111111100000000000000000000000111111111111
 11111111111111110000000000000000000000000000000000000111111111111
 11111111111111111100000000000000000000000000001100000111111111111
 11111111111111000000000000000000000000000000111100000111111111111
 11111111111000000000000000000000000000000001111110000111111111111
 11111111100000000000000000000000000000001111111110000111111111111
 11111110000000000000000000000000000000111111111110000111111111111
 11111100000000000000000001110000001111111111111110001111111111111
 11111000000000000000011111111111111111111111111110011111111111111
 11110000000000000001111111111111111100111111111111111111111111111
 11100000000000000011111111111111111111100001111111111111111111111
 11100000000001000111111111111111111111111000001111111111111111111
 11000000000001100111111111111111111111111110000000111111111111111
 11000000000000111011111111111100011111000011100000001111111111111
 11000000000000011111111111111111000111110000000000000011111111111
 11000000000000000011111111111111000000000000000000000000111111111
 11001000000000000000001111111110000000000000000000000000001111111
 11100110000000000001111111110000000000000000111000000000000111111
 11110110000000000000000000000000000000000111111111110000000011111
 11111110000000000000000000000000000000001111111111111100000001111
 11111110000010000000000000000001100000000111011111111110000001111
 11111111000111110000000000000111110000000000111111111110110000111
 11111110001111111100010000000001111100000111111111111111110000111
 11111110001111111111111110000000111111100000000111111111111000111
 11111111001111111111111111111000000111111111111111111111111100011
 11111111101111111111111111111110000111111111111111111111111001111
 11111111111111111111111111111110001111111111111111111111100111111
 11111111111111111111111111111111001111111111111111111111001111111
 11111111111111111111111111111111100111111111111111111111111111111
 11111111111111111111111111111111110111111111111111111111111111111
 
 
 */
